package com.ldc.framework.activity

import android.content.Context
import android.content.Intent
import android.os.Message
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.listener.OnRowListener2
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMActivity
import com.ldc.framework.R
import com.ldc.framework.adapter.ArticleAdapter
import com.ldc.framework.databinding.FrameworkActivityProjectsListBinding
import com.ldc.framework.model.ArticleModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

class ProjectsListActivity :
    VBMActivity<FrameworkActivityProjectsListBinding, FrameworkViewModelBase>() {
    private var articleAdapter: ArticleAdapter? = null
    private var page: Int = 0
    private var cid: String? = ""
    private var title: String? = ""

    companion object {
        private const val ARG_CID = "cid"
        private const val ARG_TITLE = "title"
        private const val REFRESH_CODE = 0x1234
        fun start(fragment: Fragment, title: String, cid: String) {
            start(fragment.requireContext(), title, cid)
        }

        fun start(context: Context, title: String, cid: String) {
            context.startActivity(Intent(context, ProjectsListActivity::class.java).also {
                it.putExtra(ARG_CID, cid)
                it.putExtra(ARG_TITLE, title)
            })
        }
    }

    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                projectList()
            }
        }
        return super.processMessage(msg)
    }


    override fun main() {

        intent?.also {
            cid = it.getStringExtra(ARG_CID)
            title = it.getStringExtra(ARG_TITLE)
        }
        initAdapter()
        viewBind?.topBar?.also {
            it.flBack.setOnClickListener { finish() }
            it.tvName.text = "$title"
        }
        viewBind?.contentView?.also {
            it.refreshView.also { rf ->
                rf.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
                    override fun onRefresh(refreshLayout: RefreshLayout) {
                        page = 0
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }

                    override fun onLoadMore(refreshLayout: RefreshLayout) {
                        page += 1
                        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                    }
                })
            }
        }
        viewBind?.statusView?.let {
            it.showLoadView()
            it.addRetryClickListener(object : OnRowListener<Int> {
                override fun onRow(v: View, data: Int) {
                    it.showLoadView("正在重试，请稍等")
                    page = 1
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }
            })
        }
        MessageUts.sendMessage(getHandler(), REFRESH_CODE)

    }

    override fun createViewBinding(): FrameworkActivityProjectsListBinding =
        FrameworkActivityProjectsListBinding.inflate(layoutInflater)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)


    //初始化适配器
    private fun initAdapter() {
        articleAdapter = ArticleAdapter().also { adapter ->
            adapter.addCollectRowListener(object : OnRowListener2<ArticleModel, Int> {
                override fun onRow(v: View, data: ArticleModel, data2: Int) {
                    if (data.collect) {
                        // 取消收藏
                        viewModel?.uncollectOriginId("${data.id}")
                            ?.observe(this@ProjectsListActivity) {
                                if (ApiUtils.isSuccess(it)) {
                                    adapter.changeDataItem(data2)
                                }
                            }
                    } else {
                        // 收藏
                        viewModel?.collect("${data.id}")?.observe(this@ProjectsListActivity) {
                            if (ApiUtils.isSuccess(it)) {
                                adapter.changeDataItem(data2)
                            }
                        }
                    }
                }

            })
            adapter.addOnRowListener(object : OnRowListener<ArticleModel> {
                override fun onRow(v: View, data: ArticleModel) {
                    ARouter.getInstance().build(RouteConf.WebViewRoute.startEnter)
                        .withString(AppConf.ARG_TITLE, data.title)
                        .withString(AppConf.ARG_URL, data.link)
                        .navigation()
                }
            })
        }
        viewBind?.contentView?.rv?.recyclerview?.also {
            it.adapter = articleAdapter
            it.layoutManager = LinearLayoutManager(it.context, LinearLayoutManager.VERTICAL, false)
            it.setHasFixedSize(true)
        }
    }

    // 系统
    private fun projectList() {

        viewModel?.articleList(page, "$cid")?.observe(this) { data ->
            viewBind?.statusView?.showContentView()
            viewBind?.contentView?.refreshView?.let { rf ->
                if (rf.state.isOpening) {
                    rf.finishRefresh()
                    rf.finishLoadMore()
                }
                rf.setNoMoreData(page == data.data?.pageCount)
            }
            if (ApiUtils.isSuccess(data)) {
                if (0 == page) {
                    articleAdapter?.newData(data.data?.datas)
                } else articleAdapter?.addNewData(data.data?.datas)
            } else {
                viewBind?.statusView?.showErrorView(data.errorMsg)
            }
            if (articleAdapter?.isEmptyData()!!) {
                viewBind?.statusView?.showEmptyView()
            }
        }
    }

}